package com.ztgf.shopping.service.shop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.BrandInfoDTO;
import com.ztgf.commodity.models.dto.CommodityCategoryDTO;
import com.ztgf.commodity.models.service.IBrandInfoService;
import com.ztgf.commodity.models.service.ICommodityCategoryService;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopCategoryRelationMapper;
import com.ztgf.shopping.models.bo.shop.ShopCategoryRelationSaveBO;
import com.ztgf.shopping.models.dto.shop.ShopBrandRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopCategoryRelationDTO;
import com.ztgf.shopping.models.service.shop.IShopCategoryRelationService;
import com.ztgf.shopping.models.vo.shop.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ztgf.common.utils.UtilConstants.isNull;

/**
 * 店铺分类表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-28 14:42:59
 */
@DubboService
public class ShopCategoryRelationServiceImpl extends ServiceImpl<ShopCategoryRelationMapper, ShopCategoryRelationDTO> implements IShopCategoryRelationService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private ShopBrandRelationServiceImpl iShopBrandRelationService;
    @DubboReference
    private IBrandInfoService iBrandInfoService;
    @DubboReference
    private ICommodityCategoryService iCommodityCategoryService;

    @Override
    public boolean add(ShopCategoryRelationSaveBO saveBO) {
        ShopCategoryRelationDTO dto = new ShopCategoryRelationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public List<ShopCategoryRelationVO> queryList(Long id) {
        ArrayList<ShopCategoryRelationVO> vos = new ArrayList<>();
        //获取关联表
        Wrapper<ShopBrandRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", id)
                .eq("status", 0);
        List<ShopBrandRelationDTO> shopBrandRelationDTOList = iShopBrandRelationService.selectList(wrapper);
        for (ShopBrandRelationDTO dto : shopBrandRelationDTOList) {
            ShopCategoryRelationVO vo = new ShopCategoryRelationVO();
            BrandInfoDTO brandInfoDTO = iBrandInfoService.selectById(dto.getBrandId());
            vo.setBrandId(dto.getBrandId());
            vo.setLogoUrl(brandInfoDTO.getLogoUrl());
            vo.setName(brandInfoDTO.getName());
            vo.setShopId(id);

            Wrapper<ShopCategoryRelationDTO> crwrapper = new EntityWrapper<>();
            crwrapper.eq("shop_id", id)
                    .eq("brand_id", dto.getBrandId())
                    .eq("is_delete", 0);
            vo.setShopCategoryRelationDTOList(this.selectList(crwrapper));
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public List<ShopCategoryRelationDTO> queryListByBrandId(Long brandId) {
        Wrapper<ShopCategoryRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("brand_id", brandId);
        wrapper.groupBy("category_id");
        return this.selectList(wrapper);
    }

    @Override
    public List<ShopCategoryVO> getCategoryByShopId(Long id) {
        return baseMapper.getCategoryByShopId(id);
    }

    @Override
    public List<CommodityCategoryTreeVO> queryTreeByBrandId(Long id) {
        Wrapper<ShopCategoryRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("brand_id", id);
        wrapper.groupBy("category_id");
        List<ShopCategoryRelationDTO> shopCategoryList = this.selectList(wrapper);
        if (shopCategoryList == null || shopCategoryList.size() <= 0) {
            return null;
        }
        List<CommodityCategoryTreeVO> root = new ArrayList<>();
        for (ShopCategoryRelationDTO shopCategoryRelationDTO : shopCategoryList) {
            List<CommodityCategoryTreeVO> byChildId = this.getByChildId(shopCategoryRelationDTO.getCategoryId(), new ArrayList<>());
            root.addAll(byChildId);
        }
        //查询最顶级的类目
        Wrapper<CommodityCategoryDTO> wrapperParent = new EntityWrapper<>();
        wrapperParent.eq("is_publish", 1).eq("status", 0)
                .eq("parent_id", 0).orderBy("sort", true);
        List<CommodityCategoryDTO> parentList = iCommodityCategoryService.selectList(wrapperParent);
        for (CommodityCategoryDTO commodityCategoryDTO : parentList) {
            CommodityCategoryTreeVO commodityCategoryTreeVO = new CommodityCategoryTreeVO();
            BeanUtils.copyProperties(commodityCategoryDTO, commodityCategoryTreeVO);
            root.add(commodityCategoryTreeVO);
        }
        //去重
        List<CommodityCategoryTreeVO> realRoot = root.stream().distinct().collect(Collectors.toList());
        //构建树形结构
        List<CommodityCategoryTreeVO> list = this.builTree(realRoot);
        List<CommodityCategoryTreeVO> real = new ArrayList<>();
        for (CommodityCategoryTreeVO categoryTreeVO : list) {
            real.addAll(categoryTreeVO.getChildList());
        }
        return real.stream().distinct().collect(Collectors.toList());
    }


    /*
     * @description:后台管理系统根据品牌id获取关联类目和店铺
     * @author: chenyu.wang
     * @date: 2020-09-21
     * @return:
     */
    @Override
    public ShopBrandRelationNewVO getBrandNewByBrandId(Long brandId) {
        ShopBrandRelationNewVO vo = new ShopBrandRelationNewVO();
        Wrapper<ShopCategoryRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("brand_id", brandId);
        wrapper.groupBy("category_id");
        List<ShopCategoryRelationDTO> relationDTOList = this.selectList(wrapper);
        if (isNull(relationDTOList)) {
            return null;
        }
        List<ShopCategoryTreeVO> list = new ArrayList<>();
        for (ShopCategoryRelationDTO shopCategoryRelationDTO : relationDTOList) {
            ShopCategoryTreeVO treeObject = this.getTreeObject(shopCategoryRelationDTO.getCategoryId());
            list.add(treeObject);
        }
        if (!isNull(list)) {
            vo.setCategoryList(list);
        }
        //获取关联店铺
        List<ShopBrandMsgVO> shopList = baseMapper.queryBrandShopByBrandId(brandId);
        if (!isNull(shopList)) {
            vo.setShopList(shopList);
        }
        return vo;
    }

    /**
     * 通过店铺修改店铺佣金
     * @param shopId
     * @param ids
     * @param dividendScaleRate
     * @return
     */
    @Override
    public boolean updateShopDividendScale(Long shopId, String ids,BigDecimal dividendScaleRate) {
        Integer flag = baseMapper.updateShopDividendScale(shopId,ids,dividendScaleRate);
        if (flag !=null && flag >0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 通过类目店铺修改店铺佣金
     * @param ids
     * @Author: liyang
     * @param dividendScale
     * @return
     */
    @Override
    public Integer updateShopDividendScaleByCategory(String ids, BigDecimal dividendScale) {
        Integer n =  baseMapper.updateShopDividendScaleByCategory(ids,dividendScale);
        return n;
    }

    /**
     * 通过10分钟定时任务修改店铺佣金
     * @param ids
     * @Author: liyang
     * @return
     */
    @Override
    public boolean updateShopDividendScaleByScheduled(String ids) {
        Integer n =  baseMapper.updateShopDividendScaleByScheduled(ids);
        return n > 0;
    }

    @Override
    public ShopCategoryRelationDTO getCategoryByShopIdAndCommodityId(Long shopId, Long commodityId) {
        return this.baseMapper.getCategoryByShopIdAndCommodityId(shopId, commodityId);
    }


    /**
     * description: 建立树形结构
     * param: [menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    public List<CommodityCategoryTreeVO> builTree(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> treeMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : getRootNode(menuList)) {
            menuNode = this.buildChilTree(menuNode, menuList);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    /**
     * description: 递归，建立子树形结构
     * param: [pNode, menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: com.ztgf.commodity.models.vo.CommodityCategoryTreeVO
     */
    private CommodityCategoryTreeVO buildChilTree(CommodityCategoryTreeVO pNode, List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> chilMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().equals(pNode.getId())) {
                chilMenus.add(this.buildChilTree(menuNode, menuList));
            }
        }
        pNode.setChildList(chilMenus);
        return pNode;
    }

    /**
     * description: 获取根节点
     * param: [menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    private List<CommodityCategoryTreeVO> getRootNode(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> rootMenuLists = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().intValue() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

    /**
     * description: 根据最终极类目id查询所有上级list
     * param: [id, list]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    public List<CommodityCategoryTreeVO> getByChildId(Long id, List<CommodityCategoryTreeVO> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        CommodityCategoryDTO dto = iCommodityCategoryService.selectById(id);
        if (dto == null) {
            return null;
        }
        if (dto.getParentId() == 0) {
            return list;
        } else {
            CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
            treeVO.setId(dto.getId());
            treeVO.setName(dto.getName());
            treeVO.setInitials(dto.getInitials());
            treeVO.setParentId(dto.getParentId());
            treeVO.setSort(dto.getSort());
            treeVO.setCode(dto.getCode());
            list.add(treeVO);
        }
        return this.getByChildId(dto.getParentId(), list);
    }

    /*
     * @description:封装类目对象
     * @author: chenyu.wang
     * @date: 2020-09-21
     * @return:
     */
    private ShopCategoryTreeVO getTreeObject(Long id) {
        ShopCategoryTreeVO shopCategoryTreeVO = new ShopCategoryTreeVO();
        //三
        CommodityCategoryDTO three = iCommodityCategoryService.selectById(id);
        shopCategoryTreeVO.setThreeCategoryName(three.getName());
        if (three.getParentId() != 0) {
            //二
            CommodityCategoryDTO two = iCommodityCategoryService.selectById(three.getParentId());
            shopCategoryTreeVO.setTwoCategoryName(two.getName());
            if (two.getParentId() != 0) {
                CommodityCategoryDTO one = iCommodityCategoryService.selectById(two.getParentId());
                shopCategoryTreeVO.setOneCategoryName(one.getName());
            }
        }
        return shopCategoryTreeVO;
    }
}
